from flask import Flask, request
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
import requests
import json

app = Flask(__name__)

@app.route('/weather')
def get_weather_temp():
    weather = {}
    code = request.args.get('code')
    if not code:
        return "需要查询的地区编码不能为空！"
    url = f"https://www.weather.com.cn/weather/{code}.shtml"

    headers = {
        "user-agent": UserAgent().random
    }
    response = requests.get(url, headers=headers)
    response.encoding = "utf-8"
    html = BeautifulSoup(response.text, "html.parser")

    # 解析未来7天总体天气
    weather["future7dData"] = parse_future_7d_weather_data(html)

    # 解析过去24小时的天气
    weather["last24hData"] = parse_last_24h_weather_data(html)

    # 解析未来整点天气
    weather["futureHourData"] = parse_future_hour_weather_data(html)

    return weather


def parse_future_7d_weather_data(html):
    result = []
    lis = html.find("div", {"id": "7d"}).find("ul", {"class":"clearfix"}).find_all("li")
    now = datetime.now()
    day = now.day
    for li in lis:
        day1 = int(li.find("h1").text.split("日")[0])
        if day1 == day:
            dayResult = {}
            dayResult["time"] = now.strftime('%Y-%m-%d 00:00:00')
            dayResult["overallWeather"] = li.find("p").text
            dayResult["temperatureRange"] = li.find("p", {"class": "tem"}).text.replace("\n", "")
            win = li.find("p", {"class": "win"})
            winDir = []
            for span in win.find_all("span"):
                winDir.append(span["title"])
            dayResult["windDirection"] = '转'.join(winDir)
            dayResult["windSpeed"] = win.find("i").text
            result.append(dayResult)

            now = now + timedelta(days=1)
            day = now.day
    return result

def parse_last_24h_weather_data(html):
    result = []

    scripts = html.find_all('script')
    for script in scripts:
        if "observe24h_data" in script.text:
            data_str = script.text.replace("var", "").replace("observe24h_data", "").replace("=", "").replace(";", "")
            data = json.loads(data_str)
            time_str = data["od"]["od0"][0:12]
            weather_data = data["od"]["od2"]
            current_time = datetime.strptime(time_str, "%Y%m%d%H%M")
            i = -24
            for d in reversed(weather_data):
                hourResult = {}
                current_time1 = current_time + timedelta(hours=i)
                i = i + 1
                hourResult["time"] = current_time1.strftime("%Y-%m-%d %H:%M:%S")
                hourResult["temperature"] = d["od22"]
                hourResult["humidity"] = d["od27"]
                hourResult["windDirection"] = d["od24"]
                hourResult["windSpeed"] = d["od25"] + "级"
                hourResult["precipitation"] = d["od26"]
                result.append(hourResult)

    return result

def parse_future_hour_weather_data(html):
    result = []
    scripts = html.find_all('script')
    for script in scripts:
        if "hour3data" in script.text:
            data_str = script.text.replace("var", "").replace("hour3data", "").replace("=", "").replace(";", "")
            data = json.loads(data_str)
            hourData = data["7d"]
            now = datetime.now()
            now_time = now.strftime('%Y年%m月')
            day = now.day
            for hd in hourData:
                for d in hd:
                    hourResult = {}
                    tmp = d.split(",")
                    day1 = int(tmp[0].split("日")[0])
                    if day1 != day:
                        now = now + timedelta(days=1)
                        now_time = now.strftime('%Y年%m月')
                        day = day1
                    hourResult["time"] = datetime.strptime(now_time + tmp[0], '%Y年%m月%d日%H时').strftime("%Y-%m-%d %H:%M:%S")
                    hourResult["temperature"] = tmp[3].replace("℃", "")
                    hourResult["overallWeather"] = tmp[2]
                    hourResult["windDirection"] = tmp[4]
                    hourResult["windSpeed"] = tmp[5]
                    result.append(hourResult)
    return result

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7000)